import axios from 'axios'
import notification from 'ant-design-vue/es/notification'

const rquest = axios.create({
  // api请求的默认前缀
})

const errorHandler = (error: any) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message,
      })
    }
    if (error.response.status === 401 && !data.result) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed',
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor 请求拦截器
rquest.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, errorHandler)
// response interceptor
rquest.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

export default rquest
